<template>
	<div class="system-role-container layout-padding">
		<div class="system-role-padding layout-padding-auto">
			<el-card shadow="hover" style="display: flex;flex-direction: column;flex: 1;height: inherit;">
				<section class="flex-c material-manage-wrapper"  style="flex: 1;height: inherit;">
					<section class="left-tree-wrapper"  style="display: flex;flex-direction: column;height: inherit;">
						<section class="flex-c add-category" @click="addCategory">
							<el-image style="width: 22px; height: 22px;" :src="folderAdd"  />
							&nbsp;<span>添加分类</span>
						</section>
						<section>
							<el-tree :data="state.treeData" node-key="id" highlight-current="true">
								<template #default="{ data }">
									<section class="dirItem font16 flex-c" :class="{isActive: state.dirId == data.group}" @click="changeDir(data.group)"
										style="justify-content: space-between; flex: 1;">
										<section class="flex-c">
											<!-- <el-icon>
												<ele-Folder />
											</el-icon> -->
											<el-image style="width: 22px; height: 22px;" :src="folder"  />
											&nbsp;&nbsp;{{ data.name }}
										</section>
										<el-dropdown v-if="data.group != 'default'" @command="handleCommand($event, data )">
											<span class="el-dropdown-link">
												<el-icon>
													<ele-MoreFilled />
												</el-icon>
											</span>
											<template #dropdown>
												<el-dropdown-menu>
													<el-dropdown-item command="edit">分类编辑</el-dropdown-item>
													<el-dropdown-item command="del">分类删除</el-dropdown-item>
													<el-dropdown-item command="delAll">删除所有</el-dropdown-item> 
												</el-dropdown-menu>
											</template>
										</el-dropdown> 
									</section>
								</template>
							</el-tree>
						</section>
					</section>

					<section class="right-material-content" style="flex-direction: column;flex: 1;height: inherit;">
						<section style="display: flex;flex-direction: column;flex: 1;height: inherit;">
							<section class="right-material-opration mb15 flex-c">
								<section>
									<el-button type="primary" @click="uploadImgFun()">上传图片</el-button>
									<el-button type="primary" @click="uploadVideoFun()">上传视频</el-button>
									<el-button type="danger" @click="batchDelete">删除图片</el-button>&nbsp;
									<el-select v-model="state.moveDirId" placeholder="图片移至" @change="handleChange">
										<el-option v-for="item in state.treeData" :key="item.group" :label="item.name" :value="item.group" />
									</el-select>
								</section>
								<section class="flex-c">
									<el-input class="width220" v-model="state.keyword" placeholder="输入图片名称搜索" @change="getFileList()"> </el-input>&emsp;
									<el-radio-group v-model="state.viewType">
										<el-radio-button :label="1">
											<el-icon><Menu /></el-icon>
										</el-radio-button>
										<el-radio-button :label="2">
											<el-icon><Expand /></el-icon>
										</el-radio-button>
									</el-radio-group>
								</section>
							</section>
							<section class="goods-img-list-grid" style="flex: 1;overflow: hidden;overflow-y:auto" v-show="state.viewType === 1">
								<section class="goods-img-list" v-if="state.informationList.length != 0">
									<section class="goods-img-item mr12 mb12" v-for="(i, index) of state.informationList" :key="index">
										<section style="position: relative;" @click.prevent.stop="selectImg(i)" >
											<el-image fit="contain" :src="i.url" :class="['goods-img', state.setList.has(i.url) ? 'active-img' : '']" />
											<span v-if="i.fileType == 1" style="width:128px;height:128px;position:absolute; 
												top:0;right:0;bottom:0;left:0; display:flex;align-items:center;justify-content:center;">
												<el-icon class="font36" style="color:#fff;background-color: rgba(0, 0, 0, 0.8);width:48px;height:48px;border-radius:50%;">
													<ele-CaretRight />
												</el-icon>
											</span>
										</section>
										<p class="goods-img-name font15">
											<el-input ref="inputXs" v-if="i.edit" v-model="i.filename" clearable @blur="editBlur($event, i, index)" class="font14" style="width: 128px;height:26px"></el-input>
											<span v-else>{{ i.filename }}</span>
										</p> 
										<section class="opration-wrapper flex-c font14">
											<span @click="deleteFile(i, index)">删除</span>
											<span @click="rename(i,index)">重命名</span>
											<span @click="lookFile(i, index)">查看</span>
										</section>
									</section>
								</section>
								<section v-else style="display: flex;flex: 1;height: -webkit-fill-available; justify-content: center;align-items: center">
									<el-empty description="暂无数据" />
								</section>
							</section>
							<el-table :data="state.informationList" v-loading="state.loading" style="width: 100%"
								@selection-change="handleSelectionChange"
								v-show="state.viewType === 2">
								<el-table-column type="selection" width="55" />
								<el-table-column prop="name" label="文件" width="80">
									<template #default="scope"> 
										<el-image style="width: 36px; height: 36px;" fit="contain" :src="scope.row.url" />
									</template>
								</el-table-column>
								<el-table-column prop="name" label="文件名称" show-overflow-tooltip>
									<template #default="scope">
										<section>
											<span v-show="!scope.row.edit">{{ scope.row.filename }}</span>
											<el-input ref="inputYs" @blur="editBlur($event, scope.row, scope.$index)" :autofocus=true
												v-model="scope.row.filename" v-show="scope.row.edit" placeholder="输入图片名称" 
											/> 
										</section>
									</template>
								</el-table-column>
								<el-table-column prop="name" label="文件格式">
									<template #default="scope"> 
										<span>{{ scope.row.extension }}</span>										
									</template>
								</el-table-column>
								<el-table-column prop="name" label="文件大小" width="120">
									<template #default="scope"> 
										{{ fileSize(scope.row.filesize) }}
									</template>
								</el-table-column>
								<el-table-column label="上传时间">
									<template #default="scope">
										<span>{{ formatDate (new Date(scope.row.createTime), 'YYYY-mm-dd HH:MM:SS') }}</span>
									</template>
								</el-table-column>
								<el-table-column label="操作人">
									<template #default="scope">
										<span>{{ scope.row.createBy }}</span>
									</template>
								</el-table-column>
								<el-table-column label="操作" align="center" width="200">
									<template #default="scope">
										<section>
											<span style="color:var(--el-color-primary);" @click="deleteFile(scope.row, scope.$index)">删除</span>
											<span style="color:var(--el-color-primary);">&nbsp;|&nbsp;</span>
											<span style="color:var(--el-color-primary);" @click="rename(i,index)">重命名 </span>
											<span style="color:var(--el-color-primary);">&nbsp;|&nbsp;</span>
											<span style="color:var(--el-color-primary);" @click="lookFile(scope.row, scope.$index)">查看</span>
										</section>
									</template>
								</el-table-column>
								<template #empty>
									<el-empty description="暂无数据" />
								</template>
							</el-table>
							<el-row justify="end">
								<el-col :span="24" class="flex-end-center">
									<el-pagination @size-change="onHandleSizeChange" @current-change="onHandleCurrentChange"
										class="mt15" :page-sizes="[10, 20, 30,40]"
										v-model:current-page="state.param.pageNum" background v-model:page-size="state.param.pageSize"
										layout="total, sizes, prev, pager, next, jumper" :total="state.total">
									</el-pagination>
								</el-col>
							</el-row>
						</section>
					</section>
				</section>
			</el-card>
		</div>
		<xgPlayVideo ref="xgPlayVideoRef" />
		<AddDirTree ref="addDirTreeRef" @refresh="getDirList()" />
		<UploadImage ref="uploadImageRef" @refresh="getDirList()" />
		<UploadVideo ref="uploadVideoRef" @refresh="getDirList()" />
	</div>
</template>

<script setup lang="ts" name="systemRole">
import Player from 'xgplayer';
import 'xgplayer/dist/index.min.css';
import { Search, Menu, Expand } from '@element-plus/icons-vue'
import { defineAsyncComponent, reactive, onMounted, ref } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { api as ViewerApi } from 'v-viewer'
import { formatDate,fileSize } from '/@/utils/formatTime';
import folderAdd from '/@/assets/svg/folderAdd.svg?url';
import folder from '/@/assets/svg/folder.svg?url';
import { dirList, fileList, dirDelete, fileUpload,fileMove,fileDelete,fileBatchDelete } from '/@/api/commodity';

const xgPlayVideo = defineAsyncComponent(() => import('/@/components/information/xgPlayVideo.vue'))
const AddDirTree = defineAsyncComponent(() => import('/@/components/information/AddCategoryTree.vue'))
const UploadImage = defineAsyncComponent(() => import('/@/components/information/UploadImage.vue'))
const UploadVideo = defineAsyncComponent(() => import('/@/components/information/UploadVideo.vue'))


const xgPlayVideoRef = ref();
const addDirTreeRef = ref();
const uploadImageRef = ref();
const uploadVideoRef = ref();

export interface Tree {
    id: number
    label: string
    pid: number
    children?: Tree[]
    value?: number,
}
// 定义变量内容
const inputXs = ref([]);
const state = reactive({
	// 视频链接地址
	centerDialogVisible:false,
	playerOptions:{},
	videoSrc:'https://v-vod-k.xiaoeknow.com/appx9lsawzb3661/video/b_u_cocv7vqumbtqp5al5le0/luxi8gqa02xv.mp4?sign=6ca64448c541e83830d241e809c64655&t=661a9cfb&us=pcleEVXLTR',
	dialogTableVisible:false,
	dirId:null,
	moveDirId:null,
	total: 0,
	loading: false,
	param: {
		search: '',
		pageNum: 1,
		pageSize: 30,
	},
	informationList: [] as Array<any>,
	parent: '',
	keyword: '',
	viewType: 1,
	count: 0,
	conutData: [] as Array<any>,
	treeData: [] as Array<Tree>,
	setList: new Set<number>(),
	srcList: null as Array<string> | null,
    previewIndex: 0,
})



// 图片上传
const uploadImgFun = () => {
	uploadImageRef.value.openDialog();
}
// 上传视频
const uploadVideoFun = () => {
	uploadVideoRef.value.openDialog();
}

// 分类切换
const changeDir = (type:any) => {
	if(state.dirId != type){
		state.dirId = type;
		getFileList();
	}
}

// 表单选中文件
const handleSelectionChange = (val: any) => {
	console.log(val);
	state.conutData = [];
	state.conutData=val;
	val.map((item:any)=>{
		state.setList.add(item.url);
	})
	state.count = val.length;
//   multipleSelection.value = val
}

// 文件重命名
const editBlur = async (event: any, item: any, index: number) => {
	if(item.filename == ''){
		return
	}
	item.edit = false
	// state.informationList[index].edit = false
	const fileListx = [{  
		id:item.id,
		filename: item.filename,
	}];
    const { results } = await fileUpload(fileListx, item.group);
	// 文件重命名
	// fileUpload
	console.log(event.target);
	event.target.blur()
}

const handleCommand =  (e: any, data: Tree) => {
	console.log(JSON.stringify(data))
	if(e === 'edit'){
		addDirTreeRef.value.openDialog('edit', data);
	}else if(e === 'delAll'){
		ElMessageBox.confirm( '确定删除该分类，此操作将删除分类下所有文件?', '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        ).then(async() => {
			const { results } = await dirDelete(data.group, 1);
			getDirList()
        })
	}else if(e === 'del') {
		ElMessageBox.confirm( '确定删除该分类，此操作将移动该分类下所有文件至默认文件夹下?', '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        ).then(async() => {
			const { results } = await dirDelete(data.group, 0);
			getDirList()
        })
    }
}

// 删除文件
const deleteFile = async (item: any, index: number) => {
	ElMessageBox.confirm( '确定删除该文件 ?','提示',
		{
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
		}
	) .then( async() => {
		const { method } = await fileDelete(item.id);
		if(method == 'success'){
			state.informationList.splice(index, 1);
			return ElMessage({
				type: 'success',
				message: '删除成功',
			})
		}
	})
}



const rename = (item: any, index: number) => {
	item.edit = true;
	// console.log(inputXs.value[index])
}

// 文件查看
const lookFile = async (item: any, index: number) => {
	if(item.fileType == 1){
		xgPlayVideoRef.value.openDialog(item.videoCover)
	}else{
		state.srcList = state.informationList.map(e => e.url)
		// state.srcList = state.informationList.filter(obj => obj.fileType == 0).map(e => e.url)
		ViewerApi({
			options: {
				initialViewIndex: index
			},
			images: state.srcList 
		});
	}
}

// 图片移动
const handleChange = async() => {
	if(state.count > 0){
		let params = state.conutData.map(obj => ({ id: obj.id }));
		ElMessageBox.confirm( '确定更改该图片分组?', '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        ).then(async() => {
			const { method } = await fileMove(params, state.moveDirId);
			if(method == 'success'){
				getDirList()
				state.count = 0;
				state.conutData = [];
				state.setList = new Set<number>();
				return ElMessage({
					type: 'success',
					message: '成功',
				})
			}
        })
	}
	state.moveDirId = null;
}

// 批量删除
const batchDelete = async() => {
	if(state.count > 0){
		let params = state.conutData.map(obj => obj.id);
		ElMessageBox.confirm( '确定删除该图片?', '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        ).then(async() => {
			const { method } = await fileBatchDelete({idList:params});
			if(method == 'success'){
				getDirList()
				state.count = 0;
				state.conutData = [];
				state.setList = new Set<number>();
				return ElMessage({
					type: 'success',
					message: '成功',
				})
			}
        })
	}
}



// 文件选择
const selectImg = (i: any) => {
    if(state.setList.has(i.url)) {
        state.setList.delete(i.url)
		let x = state.conutData.findIndex(obj => obj.id === i.id)
		state.conutData.splice(x,1)
        state.count --
    } else {
		// 选中得文件对象
		state.conutData.push(i);
		// 选中得文件地址
        state.setList.add(i.url);
        state.count ++
    }
    if(state.setList.size === 0) {
		state.conutData = [] as Array<any>;
        state.count = 0
    }
};


// 分页点击 条数
const onHandleSizeChange = (val: number) => {
	state.param.pageSize = val;
	getFileList();
}; 
// 分页点击
const onHandleCurrentChange = (val: number) => {
	state.param.pageNum = val;
	getFileList();
};

const addCategory = () => {
	addDirTreeRef.value.openDialog('add');
}

// 获取分类列表
const getDirList = async () => {
	state.loading = true;//不用传参， 请求得入参在上面都定义了 param这里吗？
	const { results } = await dirList();
	state.treeData = results
	state.loading = false;
	if(results.length > 0){
		state.dirId = results[0].group
		getFileList();
	}
}

// 获取分类下文件列表
const getFileList = async () => {
	state.loading = true;
	let search = { group: [state.dirId,"="],fileName:[state.keyword,"="] }
	let params = {
		page:state.param.pageNum,
		list_rows:state.param.pageSize,
		search:JSON.stringify(search),
	}
	const { results } = await fileList(params);
	state.informationList = results.records;
	state.loading = false;
	state.total = results.total;
	state.loading = false;
}


// 页面加载时
onMounted(() => {
	getDirList()
});
</script>
<style scoped lang="scss">
@import '../../../theme/mixins/index.scss';
:deep(.el-card__body){
	display: flex;
	flex-direction: column;
	flex: 1;
	height: inherit;
	.el-table{
		flex: 1;
		.el-table__inner-wrapper::before{
			background: none !important;
		}
	}
}
:deep() {
    .el-tree-node__content {
        height: auto !important;
    } 
}
.flex-c {
    display: flex;
    align-items: center;
}
.add-category{
	padding: 10px 5px;
	cursor: pointer;
}
.material-manage-wrapper{
	align-items: flex-start;
	.left-tree-wrapper{
		width: 200px;
		border-right: 1px solid #ededed;
		.dirItem{
			display: flex;
			align-items: center;
			padding:5px 15px;
		}
		.isActive{
			border-right: 2px solid var(--el-color-primary) !important;
			background-color:var(--el-color-primary-light-9);
		}
		:deep(.el-tree-node__content){
			padding: 0;
		}
		

	}
	.right-material-content{
		flex: 1;
		padding-left: 15px;
		.right-material-opration{
			justify-content: space-between;
			
		}
		
	}
	.goods-img-list-grid{
		.goods-img-item{ 
			.img-index{
				position: absolute;
				bottom: 12px;
				right: 12px;
				width: 20px;
				height: 20px;
				font-size: 13px;
				color: #fff;
				background-color: #217ef7;
				text-align: center;
				line-height: 20px;
				border-radius: 50%;
			}
			&:hover span {
				display: block;
			}
            }
            .goods-img-list{
                display: flex;
                flex-wrap: wrap;
            }
            .goods-img-name{
                width: 128px;
                text-align: center;
                overflow:hidden;
                text-overflow:ellipsis;
                white-space:nowrap;
				span{
					padding:0 10px;
				}
            }
            .goods-img{
                width: 128px;
                height: 128px; 
                object-fit: cover; 
                border-radius: 6px;
                border: 2px solid #ffffff;
                cursor: pointer;
                padding: 4px;
                border: 1px solid #fff;
                &:hover {
                    border: 1px solid #409EFF;
                }
            }
            .active-img {
                border: 1px solid #409EFF;
            }
        }
        .opration-wrapper {
            font-size: 12px; 
            color: #409EFF;
            text-align: center;
            height: 20px;
            justify-content: space-between;
            margin: 0 5px;
            
            span{
                cursor: pointer;
                display: none;
            } 
		}
	
	:deep(.el-tree-node__expand-icon.is-leaf){
		display: none;
	}
}
	#xgPlayVideo{
		position: fixed;
		top: 0;
		left: 0;
		bottom: 0;
		right: 0;
		height: 0;
		z-index: 99999;
		background-color: var(--el-overlay-color-lighter);
	}
</style>

